package com.ewzj.bigdata.mvp.presenter

import android.app.Application
import android.content.Intent
import android.net.Uri
import android.support.v7.app.AppCompatActivity
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.webkit.JavascriptInterface
import com.ewzj.bigdata.R
import com.ewzj.bigdata.app.config.AppKey
import com.ewzj.bigdata.app.extensions.loadMiwoUrl
import com.ewzj.bigdata.app.utils.Apputils
import com.ewzj.bigdata.app.utils.RxUtils
import com.ewzj.bigdata.mvp.contract.HourseWebActivityContract
import com.ewzj.bigdata.mvp.contract.NewsWebActivityContract
import com.ewzj.bigdata.mvp.model.bean.*
import com.ewzj.bigdata.mvp.model.reqbean.ReqNormalCollect
import com.ewzj.bigdata.mvp.model.reqbean.ReqPraise
import com.ewzj.bigdata.mvp.model.reqbean.Reqcomentbean
import com.ewzj.bigdata.mvp.model.rspbean.*
import com.ewzj.bigdata.mvp.ui.activity.LoginActivity
import com.ewzj.bigdata.mvp.ui.view.ObservableWebView
import com.github.lzyzsd.jsbridge.BridgeHandler
import com.github.lzyzsd.jsbridge.BridgeWebView
import com.github.lzyzsd.jsbridge.CallBackFunction
import com.google.gson.Gson
import com.jess.arms.base.App
import com.jess.arms.mvp.BasePresenter
import com.jess.arms.utils.DataHelper
import com.jess.arms.utils.UiUtils
import com.jess.arms.widget.CustomPopupWindow
import com.umeng.socialize.ShareAction
import com.umeng.socialize.UMShareListener
import com.umeng.socialize.bean.SHARE_MEDIA
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.media.UMWeb
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import me.jessyan.rxerrorhandler.core.RxErrorHandler
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber
import okhttp3.RequestBody
import org.w3c.dom.Text
import java.util.*
import java.util.concurrent.TimeUnit
import javax.inject.Inject

/**
 * author:zhangjing
 * 作用:
 * return:
 */
class NewsWebActivityPresenter @Inject constructor(val rxErrorHandler: RxErrorHandler, val mGson: Gson, val mErrorHandler: RxErrorHandler, val application: Application, view: NewsWebActivityContract.View, model: NewsWebActivityContract.Model) : BasePresenter<NewsWebActivityContract.Model, NewsWebActivityContract.View>(model, view) {
    lateinit var webview: ObservableWebView
    val context = mRootView as AppCompatActivity
    var replayBean: JsReplayBean? = null
    private var zanfunction: CallBackFunction? = null
    private var talkfunction: CallBackFunction? = null
    private var linkfunciton: CallBackFunction? = null

    val apiToken by lazy { DataHelper.getStringSF(context, AppKey.API_TOKEN) }
    //    回复还是评论
    var commentType: Int = 1

    fun addScanRecord(url: String) {
        mModel.read(url).compose(RxUtils.applySchedulers(mRootView)).subscribe(object : ErrorHandleSubscriber<BaseData<Any>>(mErrorHandler) {
            override fun onNext(t: BaseData<Any>) {

            }

        })
    }

    fun initBridgeWebview(bridgewebview: ObservableWebView, url: String) {
        this.webview = bridgewebview
        webview.registerHandler("talkTalk") { data, function ->
            talkfunction = function
            talkTalk(data)
        }
        webview.registerHandler("zanTalk") { data, function ->
            zanfunction = function
            zanTalk(data)
        }
        webview.registerHandler("linkOther") { data, function ->
            linkfunciton = function
            linkOther(data, function)
        }
        webview.registerHandler("share_out") { data, function ->
            share_out(data)
            function.onCallBack("")
        }
        webview.registerHandler("read_book") { data, function ->
            readbook(data)
            function.onCallBack("")
        }
        (webview as BridgeWebView).loadMiwoUrl(url)
    }

    //    回复评论
    fun talkTalk(json: String) {
        if (!Apputils.Utils.checkIsLogin(context)) {
            LoginActivity.startLoginActivity(context)
            return
        }
        replayBean = mGson.fromJson(json, JsReplayBean::class.java)
        AndroidSchedulers.mainThread().createWorker().schedule {
            mRootView.showComment()
            mRootView.resetHint(replayBean!!.tishi)
        }
        commentType = 2

    }

    fun zanTalk(json: String) {
        if (!Apputils.Utils.checkIsLogin(context)) {
            LoginActivity.startLoginActivity(context)
            return
        }
        Observable.just(json).map { t -> mGson.fromJson(json, JsCommentbean::class.java) }
                .map { t -> ReqPraise(t.groupId, t.id, 1) }
                .flatMap { t -> mModel.doPraise(t) }
                .compose(RxUtils.applySchedulers(mRootView))
                .subscribe(object : ErrorHandleSubscriber<BaseData<String>>(rxErrorHandler) {
                    override fun onNext(t: BaseData<String>) {
                        zanfunction!!.onCallBack(json)
                    }


                })
    }

    private fun linkOther(json: String, function: CallBackFunction) {
//        UiUtils.SnackbarText(json)
        Observable.just(json).map { t -> mGson.fromJson(t, InfoBean::class.java) }.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : ErrorHandleSubscriber<InfoBean>(mErrorHandler) {
                    override fun onNext(databean: InfoBean) {
                        if (!databean.title.isNullOrEmpty()){
                            mRootView.resetTitle(databean.title)
                        }
                        mRootView.reloadurl(databean)
                    }
                })

    }

    fun share_out(json: String) {
        val shareDataBean = mGson.fromJson(json, ShareDataBean::class.java)
        when (shareDataBean.getType()) {
            1 ->
                ShareWeb(shareDataBean, SHARE_MEDIA.QQ)
            2 ->
                //                qq空间
                ShareWeb(shareDataBean, SHARE_MEDIA.QZONE)
            3 ->
                //                新浪
                ShareWeb(shareDataBean, SHARE_MEDIA.SINA)
            4 ->
                //                微信
                ShareWeb(shareDataBean, SHARE_MEDIA.WEIXIN)
            5 ->
                //                朋友圈
                ShareWeb(shareDataBean, SHARE_MEDIA.WEIXIN_CIRCLE)
        }
    }

    private fun readbook(data: String) {
        Observable.just(data)
                .map { t -> mGson.fromJson(data, UrlBean::class.java) }.observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    t ->  run{
                    mRootView.hideComment()
                    webview.loadUrl(t.url)
                }
//                    UiUtils.SnackbarText("打开弹框哪种webview")
                })

        //        UiUtils.makeText(data);
    }

    fun doComment(content: String, homeBean: InfoBean) {
        if (content.isNullOrEmpty()) {
            when (commentType) {
                1 -> UiUtils.SnackbarText("评论内容不能为空哟～")
                2 -> UiUtils.SnackbarText("回复内容不能为空哟～")
            }
            return
        }
        Observable.just(content).map { t ->
            val reqcomment = Reqcomentbean()
            kotlin.run {
                reqcomment.setContent(content)
                if (commentType == 1) {
                    reqcomment.setList_id(homeBean.id.toInt())
                    reqcomment.setTable_id(homeBean.groupId.toInt())
                } else {
                    reqcomment.setList_id(replayBean!!.getId())
                    reqcomment.setTable_id(replayBean!!.getGroupId())
                    reqcomment.setId(replayBean!!.getTalkId())
                }
            }
            reqcomment
        }.flatMap { t -> mModel.docomment(t) }
                .compose(RxUtils.applySchedulers(mRootView))
                .subscribe(object : ErrorHandleSubscriber<BaseData<CommentBean>>(mErrorHandler) {
                    override fun onNext(t: BaseData<CommentBean>) {
                        mRootView.resetHint("请输入你的评论")
                        if (commentType == 1) {
                            UiUtils.SnackbarText("评论成功")
                            webview.callHandler("afterTalk", mGson.toJson(t.data), CallBackFunction { data -> UiUtils.SnackbarText(data) })
                        } else {
                            val jsReplayBean = JsReqcommentBean()
                            jsReplayBean.nickname = t.data!!.getNickname()
                            jsReplayBean.setReply(t.data!!.getContent())
                            jsReplayBean.setTalkId(replayBean!!.getTalkId().toString() + "")
                            jsReplayBean.setGroupId(replayBean!!.getGroupId().toString() + "")
                            jsReplayBean.setListId(replayBean!!.getId().toString() + "")
                            jsReplayBean.setTishi(replayBean!!.getTishi())
                            UiUtils.SnackbarText("回复成功")
                            val json = mGson.toJson(jsReplayBean)
                            talkfunction!!.onCallBack(json)
                        }
                        commentType = 1
                    }

                })
    }


    override fun onDestroy() {

        super.onDestroy()

    }


    fun ShareWeb(infodata: ShareDataBean, share: SHARE_MEDIA) {
        val web = UMWeb(infodata.shareUrl)
        if (!infodata.shareThumb.isNullOrEmpty()){
            val thumb = UMImage(context, infodata.shareThumb)
            web.setThumb(thumb)
        }else{
            val thumb = UMImage(context, R.drawable.share_default)
            web.setThumb(thumb)
        }
        if (TextUtils.isEmpty(infodata.shareSummary)){
            web.description = "觅窝.房产新媒体"
        }else{
            web.description = infodata.shareSummary
        }
        web.title = infodata.shareName
        ShareAction(context).withMedia(web).setPlatform(share).setCallback(AppKey.umShareListener).share()
    }
    fun ShareWeb(infodata: InfoBean, share: SHARE_MEDIA) {
        val web = UMWeb(infodata.go_url)
        if (!infodata.thumb.isNullOrEmpty()){
            val thumb = UMImage(context, infodata.thumb)
            web.setThumb(thumb)
        }else{
            val thumb = UMImage(context, R.drawable.share_default)
            web.setThumb(thumb)
        }
        if(TextUtils.isEmpty(infodata.summary)){
            web.description =  "觅窝.房产新媒体"
        }else{
            web.description = infodata.summary
        }

        web.title = infodata.title
        ShareAction(context).withMedia(web).setPlatform(share).setCallback(AppKey.umShareListener).share()
    }
    fun doCollect(infoBean: InfoBean){
        Observable.just(infoBean).map { t ->
            val reqNormalCollect = ReqNormalCollect()
            kotlin.run {
                reqNormalCollect.list_id = infoBean.id
                reqNormalCollect.table_id = infoBean.getGroupId()
            }
            reqNormalCollect
        }.flatMap { t -> mModel.doCollect(t) }
                .compose(RxUtils.applySchedulers(mRootView))
                .subscribe(object : ErrorHandleSubscriber<BaseData<Any>>(mErrorHandler) {
                    override fun onNext(t: BaseData<Any>) {
//                        mRootView.setCollectState()
                        if (AppKey.mchaneObject is InfoBean){
                            if ((AppKey.mchaneObject as InfoBean).is_collect==1){
                                (AppKey.mchaneObject as InfoBean).is_collect=0
                            }else{
                                (AppKey.mchaneObject as InfoBean).is_collect=1
                            }
                        }else if (AppKey.mchaneObject is RspOriginBean){
                            if ((AppKey.mchaneObject as RspOriginBean).is_collect==1){
                                (AppKey.mchaneObject as RspOriginBean).is_collect=0
                            }else{
                                (AppKey.mchaneObject as RspOriginBean).is_collect=1
                            }
                        }else if (AppKey.mchaneObject is CollectionBean){
                            if ((AppKey.mchaneObject as CollectionBean).is_collect==1){
                                (AppKey.mchaneObject as CollectionBean).is_collect=0
                            }else{
                                (AppKey.mchaneObject as CollectionBean).is_collect=1
                            }
                        }
                    }

                }
                )
    }
}